package com.ksyun.campus.metaserver.mq.consumer;

import com.ksyun.campus.metaserver.service.SyncMetaService;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.support.DefaultRocketMQListenerContainer;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class SyncMetaDataConsumerManager {

    private final GenericApplicationContext context;
    private final SyncMetaService syncMetaService;
    // 停止时暂存监听容器
    @Getter
    @Setter
    private DefaultRocketMQListenerContainer defaultRocketMQListenerContainer;
    @Getter
    @Setter
    private String defaultRocketMQListenerContainerBeanName;
    public void startConsumer() {
        if (!context.containsBean("syncMetaDataConsumer")) {
            context.registerBean("syncMetaDataConsumer", SyncMetaDataConsumer.class, () -> new SyncMetaDataConsumer(syncMetaService));
            log.info("成功启动消费者");
        } else {
            log.info("消费者已在运行中");
        }
    }

    public void stopConsumer() {
        // 获取监听容器的名字（应该只有一个）
        String[] listenerContainerBeanNames = context.getBeanNamesForType(DefaultRocketMQListenerContainer.class);
        if(listenerContainerBeanNames.length==0){
            // 还是被注销状态 无需移除
            log.info("消费者未运行");
            return;
        }
        String defaultRocketMQListenerContainerBeanName = listenerContainerBeanNames[0];
        DefaultRocketMQListenerContainer defaultRocketMQListenerContainer = context.getBean(defaultRocketMQListenerContainerBeanName, DefaultRocketMQListenerContainer.class);
        if (context.containsBean(defaultRocketMQListenerContainerBeanName)) {
            // 暂存
            this.setDefaultRocketMQListenerContainer(defaultRocketMQListenerContainer);
            this.setDefaultRocketMQListenerContainerBeanName(defaultRocketMQListenerContainerBeanName);
            context.removeBeanDefinition(defaultRocketMQListenerContainerBeanName);
        }
        if (context.containsBean("syncMetaDataConsumer")) {
            context.removeBeanDefinition("syncMetaDataConsumer");
            log.info("成功停止消费者");
        } else {
            log.info("消费者未运行");
        }
    }
}